using Assets.Scripts.Controllers;
using Assets.Scripts.Entities;
using Assets.Scripts.SO;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

namespace Assets.Scripts.UI
{
    internal class UpgradeItem : MonoBehaviour
    {
        [SerializeField] private ScriptableUpgrade _scriptableUpgrade;

        [SerializeField] private Button _buyButton;

        [SerializeField] private TMP_Text _titleText;
        [SerializeField] private TMP_Text _descriptionText;
        [SerializeField] private TMP_Text _levelText;
        [SerializeField] private TMP_Text _priceText;

        [SerializeField] private Color _normalPriceColor;
        [SerializeField] private Color _dangerPriceColor;

        private void Start()
        {
            UpdateState();

            _buyButton.onClick.AddListener(HandleClick);
        }

        private void HandleClick()
        {
            var price = _scriptableUpgrade.UpgradePrices[_scriptableUpgrade.Level];
            if (EconomyController.Instance.HasEnoughBalance(Common.CurrencyId.Dollars, price))
            {
                EconomyController.Instance.ChangeBalance(Common.CurrencyId.Dollars, -price);
                PlayerPrefs.SetInt(_scriptableUpgrade.SaveKey, _scriptableUpgrade.Level + 1);
                SoundsController.Instance.Play(Common.SoundId.Upgrade);

                UpdateState();

                // todo: just hack
                FindObjectOfType<JumpStation>().UpdateState();
                FindObjectOfType<TrampolineLimits>().UpdateState();
            }
        }

        private void UpdateState()
        {
            _titleText.text = _scriptableUpgrade.Title;
            _descriptionText.text = _scriptableUpgrade.Description;

            _levelText.text = $"{_scriptableUpgrade.Level} <#b3bedb>/ {_scriptableUpgrade.UpgradePrices.Length}";

            if (_scriptableUpgrade.Level < _scriptableUpgrade.UpgradePrices.Length)
            {
                var price = _scriptableUpgrade.UpgradePrices[_scriptableUpgrade.Level];
                var hasEnoughMoney = EconomyController.Instance.HasEnoughBalance(Common.CurrencyId.Dollars, price);

                _priceText.text = _scriptableUpgrade.UpgradePrices[_scriptableUpgrade.Level].ToString("N0");
                _priceText.color = hasEnoughMoney ? _normalPriceColor : _dangerPriceColor;
                _buyButton.interactable = hasEnoughMoney;
            }
            else
            {
                _priceText.text = "MAXED";
                _buyButton.interactable = false;
            }
        }
    }
}
